import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { File } from './entities/file.entity';
import { User } from '../user/entities/user.entity';
import * as fs from 'fs';
import { GetFileFilterDto } from './dto/getFileFilterDto';
import { IPaginationOptions, paginate, Pagination } from '../utils/paginate';

@Injectable()
export class FileService {
  constructor(
    @InjectRepository(File)
    private repository: Repository<File>,
  ) {}
  async create(file, user: User): Promise<string> {
    console.log(file);
    await file.forEach((item) => {
      const {
        originalname: name,
        mimetype: type,
        filename: saveName,
        path: url,
        size,
      } = item;
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const file = this.repository.create({
        name,
        type,
        saveName,
        url,
        size,
        user,
      });
      this.repository.save(file);
    });
    return '上传成功！';
  }

  async findAll(
    getFileFilterDto: GetFileFilterDto,
    options: IPaginationOptions,
  ): Promise<Pagination<File>> {
    const { search, size } = getFileFilterDto;
    const query = this.repository.createQueryBuilder('file');
    if (size) {
      query.andWhere('LOWER(file.size) LIKE LOWER(:size)', { size });
    }
    if (search) {
      //'LOWER(user.username) LIKE LOWER(:search) OR LOWER(user.description) LIKE LOWER(:search)'
      query.andWhere(
        'LOWER(file.name) LIKE LOWER(:search) OR LOWER(file.url) LIKE LOWER(:search)',
        {
          search: `%${search}%`,
        },
      );
    }
    query.andWhere('file.isDelete = 0');
    return await paginate<File>(query, options);
  }

  async findOne(id: string) {
    const file = await this.repository.findOneBy({ id, isDelete: 0 });
    if (!file) {
      throw new NotFoundException(`参数${id}没有找到！`);
    }
    return file;
  }

  async remove(id: string) {
    const fond = await this.findOne(id);
    if (!fond.id) {
      throw new NotFoundException(`参数 ${id} 没有找到！`);
    }
    await fs.unlink(fond.url, (err) => {
      if (err) throw err;
      console.log('文件已删除！');
    });
    await this.repository.delete(id);
  }
}
